package com.codebyorder.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codebyorder.entity.Ebook;
import com.codebyorder.mapper.EbookMapper;
import com.codebyorder.req.EbookQueryReq;
import com.codebyorder.req.EbookSaveReq;
import com.codebyorder.resp.CommonResp;
import com.codebyorder.resp.EbookQueryResp;
import com.codebyorder.resp.PageResp;
import com.codebyorder.service.EbookService;
import com.codebyorder.util.CopyUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/ebook")
public class EBookController {

    @Resource
    private EbookMapper ebookMapper;
    @Resource
    private EbookService ebookService;

    @GetMapping("/list")
    public CommonResp<PageResp<EbookQueryResp>> list(@Valid EbookQueryReq ebookQueryReq) {
        CommonResp<PageResp<EbookQueryResp>> resp = new CommonResp<>();
        resp.setContent(ebookService.ebookToResp(ebookQueryReq));
        return resp;
    }

    @GetMapping("/all")
    public List<EbookQueryResp> all(Long category2id) {
        QueryWrapper<Ebook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category2_id",category2id);
        List<Ebook> ebooks = ebookMapper.selectList(queryWrapper);
        return CopyUtil.copyList(ebooks, EbookQueryResp.class);
    }

    @PostMapping("/save")
    public CommonResp<Object> save(@Valid @RequestBody EbookSaveReq ebookSaveReq) {
        Ebook ebook = CopyUtil.copy(ebookSaveReq, Ebook.class);
        if (ebook.getId() == null) {
            ebookMapper.insert(ebook);
        } else {
            ebookMapper.updateById(ebook);
        }
        return new CommonResp<>();
    }

    @DeleteMapping("/delete/{id}")
    public CommonResp<Object> delete(@PathVariable Long id) {
        ebookMapper.deleteById(id);
        return new CommonResp<>();
    }

}
